var box = null;
var tab = null;
var type_id = 1;
var tselect = null;
var dlg_type = null;
var data_url = "ajax.php?page=set&cmd=sel&type=";

$(function(){
	box = $("#contentBox");
	tselect = $('#re_types_select');
	dlg_type = $("#type_id");
	init();
});

function init()
{
	type_id = getCookie('replBox');
	if(type_id == null) type_id = 1;
	tselect.val(type_id);

	tselect.change(function() {
		type_id = tselect.val();
		dlg_type.val(type_id);
		setReplaceFieldVisible(type_id);
		tab.fnReloadAjax(data_url + type_id);
		// console.log(type_id);
		setCookie('replBox', type_id);
	});	
	
	
    box.html(
		'<button id="btnAddNewRow">Добавить</button>'+
		'<button id="btnDeleteRow">Удалить</button>'+
		'<table cellpadding="0" cellspacing="0" border="0" class="display" id="tab"></table>' );
	tab = $('#tab', box);
    tab.dataTable( {
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bJQueryUI": false,
		"bInfo": true,
		"bFilter": true,
		"bAutoWidth": false,
		"iDisplayLength": 25,
		"bServerSide": false,
		"sAjaxSource": data_url + type_id,
		/*
		id, re_find, re_repl, company_id, user_id, type_id
        */
        "aoColumns": [
            { "sTitle": "id", "bVisible": false },
            { "sTitle": "Название", "sWidth": "20%" },
            { "sTitle": "Искать", type: "textarea"},
            { "sTitle": "Заменить на", type: "textarea", "bVisible": type_id > 1 },
            { "sTitle": "company_id", "bVisible": false },
			{ "sTitle": "user_id", "bVisible": false },
            { "sTitle": "type_id", "bVisible": false }
		],
		"oLanguage": {
			"oPaginate": {
				"sNext": "След.",
				"sFirst": "Первая",
				"sLast": "Послед.",
				"sPrevious": "Пред."
			},
			"sSearch": "Поиск:",
            "sZeroRecords": "Ничего не выбрано",
            "sInfo": "_START_-_END_ из _TOTAL_",
            "sInfoEmpty": "Показано от 0 до 0 из 0 строк",
            "sInfoFiltered": "(Доступно _MAX_)"
        }
    } ).makeEditable({
		sUpdateURL: "ajax.php?page=set&cmd=upd&type="+ type_id,
        sAddURL: "ajax.php?page=set&cmd=ins&type=" + type_id,
        sDeleteURL: "ajax.php?page=set&cmd=del",
		sAddNewRowFormId: "formAddNewRow",
		"aoColumns" : [
			{},
			{
				type: 'textarea',
				submit:'Сохранить',
				fnOnCellUpdated: function(sStatus, sValue, row, column, settings)
				{
				}
			},
			{
				type: 'textarea',
				submit:'Сохранить',
				fnOnCellUpdated: function(sStatus, sValue, row, column, settings)
				{
				}
			}
		],
		fnOnDeleting: function (tr, id, fnDeleteRow) {
			// console.log(print_r(tr[0].childNodes[0]));
			if(confirm('Вы действительно хотите удалить клиента ['+ tr[0].childNodes[0].innerText +'] ?'))
			{
					fnDeleteRow(id);
			}
		}
	});

	setReplaceFieldVisible(type_id);
}


$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
    if ( typeof sNewSource != 'undefined' && sNewSource != null )
    {
        oSettings.sAjaxSource = sNewSource;
    }
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
    var aData = [];
 
    this.oApi._fnServerParams( oSettings, aData );
     
    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );
         
        /* Got the data - add it to the table */
        var aData =  (oSettings.sAjaxDataProp !== "") ?
            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
         
        for ( var i=0 ; i<aData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, aData[i] );
        }
         
        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        that.fnDraw();
         
        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw( false );
        }
         
        that.oApi._fnProcessingDisplay( oSettings, false );
         
        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback != null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
}
 
 
function setReplaceFieldVisible(type_re_id)
{
	if(type_re_id > 1)
	{
		tab.fnSetColumnVis( 3, true );
		$("#replBox").show();
	}
	else
	{
		tab.fnSetColumnVis( 3, false );
		$("#replBox").hide();
		$("#re_repl").val("");
	}
}